package com.abel.bigwater.dataserver.model.kming

import io.netty.buffer.ByteBuf
import org.slf4j.LoggerFactory

class TermUploadReqData(_pduLen: Int = -1) : TermData(KmingDataType.TermUploadReq, _pduLen) {

    var longitude: Float? = null

    var latitude: Float? = null

    var reserve: Long = 0

    var rtuVolt: Int? = null

    var meterVolt: Int? = null

    var rssi: Short? = null

    /**
     * one unsigned-byte.
     */
    var channelCount: Int = 0

    var channelList: ArrayList<KmingChannelType> = ArrayList()

    override fun bufLength() = 1 + 8 + 4 + 2 + 2 + 1 + 1 + 2 * channelCount

    override fun parseBuf(buf: ByteBuf): Boolean {
        if (pduLen < 0) {
            throw IllegalArgumentException("dataLen should be initialized before parsing")
        }

        buf.apply {
            skipBytes(1)

            longitude = readFloatLE()
            latitude = readFloatLE()

            reserve = readUnsignedIntLE()

            rtuVolt = readUnsignedShortLE()
            meterVolt = readUnsignedShortLE()
            rssi = readUnsignedByte()

            channelCount = readUnsignedByte().toInt()

            for (i in 0..(channelCount - 1)) {
                val kc = readUnsignedShort()
                val kt = KmingChannelType.findByCode(kc)
                if (kt != null) {
                    channelList.add(kt)
                } else {
                    lgr.error("unknown channel type: ${kc.toString(16)}H")
                }
            }
        }

        return true
    }

    override fun pack(buf: ByteBuf) {
        buf.alloc().buffer().apply {
            writeByte(type.code.toInt())

            writeFloatLE(longitude ?: 0.0F)
            writeFloatLE(latitude ?: 0.0F)

            writeIntLE(reserve.toInt())

            writeShortLE(rtuVolt!!)
            writeShortLE(meterVolt ?: 0)

            writeByte(rssi!!.toInt())

            writeByte(channelCount)

            for (i in 0..(channelCount - 1)) {
                writeShort(channelList[i].code)
            }

            buf.writeBytes(this)
        }
    }

    override fun toString(): String {
        return "{type:$type,lat:$latitude,lng:$longitude,rtu:$rtuVolt,channel:${channelList.joinToString()}}"
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(TermUploadReqData::class.java)
    }
}